package com.atguigu.gulimall.search.service.impl;

import com.atguigu.common.utils.PublicUtils;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.vo.searchParam;
import com.atguigu.gulimall.search.vo.SearchResult;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author ct_start
 * @create 2022 -03 -13
 **/
@Service("mallSearchService")
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient client;

    // 这里用来接收页面传递搜索的vo 返回 检索的结果
    @Override
    public SearchResult search(searchParam param) {
        // 1. 动态构建出需要检索的DSL条件
        SearchRequest search=buildSearchRequest(param);
        SearchResult result = null;
        try {
            // 2.准备检索请求
            SearchResponse search1 = client.search(search, GulimallElasticSearchConfig.COMMON_OPTIONS);
            // 3. 封装响应数据，封装成我们指定的格式
            result= buildSearchResult(search1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;

    }

    /**
     * 构建检索出来的结果集
     * @param search1
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse search1) {
        return null;
    }

    /**
     * 准备检索请求
     * @return
     */
    private SearchRequest buildSearchRequest(searchParam param) {
        SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();
        // 所有请求的构建都要通过这个sourceBuilder

        //1. 模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存）
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            //1.1 must的模糊匹配
        if (StringUtils.isEmpty(param.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",param.getKeyword()));
        }
            //1.2 构造filter filter里面有很多层我们需要一层一层的构建
                //1.2.1 根据三级分类来过滤，如果三级分类不为空
        if (PublicUtils.isEmpty(param.getCatalog3Id())){
            // termQuery 为不分词检索
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",param.getCatalog3Id()));
        }
        sourceBuilder.query(boolQueryBuilder);
        //2. 排序 分页 高亮 todo 

        // 3. 聚合分析



        new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);

        return  null;
    }
}
